<template>
  <div class="update-ptoto">
    <img :src="img" class="img" ref="img" />
    <div class="tab">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConFm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import {updatePhotoImage} from "@/api/user";
export default {
  name: "UpdatePhoto",
  data() {
    return {
      cropper: null,
    };
  },
  props: {
    img: {
      type: [String, Object],
      required: true,
    },
  },
  mounted() {
    const image = this.$refs.img;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move", //后面图片可以拖动
      aspectRatio: 1, //比例
      // autoCropArea: 1,
      cropBoxMovable: false, //截图区域是否移动
      cropBoxResizable: false, //缩放
      background: false, //背景
      // movable:true
    });
    // console.log(cropper);
  },
  methods: {
    onConFm() {
      // 基于服务端方法裁接
      // console.log(this.cropper.getData());
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updatePhotoImage(blob)
      })
    },
    async updatePhotoImage(blob) {
      this.$toast.loading({
        message: "保存中",
        forbidClick: true,
        duration: 0,
      });
      try {
        // uupdatePhotoImag({      })
        // ptoto:blob
        // 如果接口要求Content-type是multipart/form-data
        // 必须传递FormData对象
        // application/json   普通js对象
        const formData = new FormData();
        formData.append("photo", blob);
        const { data } = await updatePhotoImage(formData);
        //  关闭弹出层
        // 更新视图
        this.$emit("close");
        this.$emit("update-photo", data.data.photo);
        this.$toast.success("更新成功");
      } catch (err) {
        this.$toast.fail("更新失败");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.update-ptoto {
  background-color: #fff;
  height: 100%;
  .tab {
    position: fixed; //固定定位
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel .confirm {
      width: 90px;
      height: 90px;
      font-size: 25px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
  .img {
    display: block;
    max-width: 100%;
  }
}
</style>